﻿using AgileConfig.Client;
using Autofac;
using Autofac.Extensions.DependencyInjection;
using Micro.Core.Packages;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Hosting;

namespace Microsoft.Extensions.DependencyInjection
{
    /// <summary>
    /// AgileConfig配置中心
    /// </summary>
    public class AgileConfigPack : BasePackage
    {

        public override PackLevel Level => PackLevel.Framework;

        public override IServiceCollection AddServices(IServiceCollection services)
        {
            return base.AddServices(services);
        }

        public override void UsePack(WebApplication app)
        {
            //app.
            base.UsePack(app);
        }

        public override void UseHostBuilder(IHostBuilder hostBuilder, IServiceProvider services)
        {
            IConfiguration configuration = services.GetService<IConfiguration>()!;
            if (configuration["AgileConfig:Enabled"].ToBool())
            {
                string configPath = configuration["AgileConfig:ConfigPath"] ?? "appsettings.json";
                hostBuilder.UseAgileConfig(new ConfigClient(configPath), e => Console.WriteLine($"config changed , action:{e.Action} key:{e.Key}"));
                //hostBuilder.UseAgileConfig(e => Console.WriteLine($"config changed , action:{e.Action} key:{e.Key}"));
            }
        }

    }
}